/* Includes ------------------------------------------------------------------*/
#include <rtthread.h>

#include "stm32f1xx_hal.h"
#include "gpio.h"
#include "uart.h"

struct rt_semaphore sem;

#define THREAD_STACK_SIZE 1024
#define THREAD_PRIORITY 8
#define THREAD_TIMESLICE 10

static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;
static rt_thread_t tid3 = RT_NULL;
static rt_mutex_t mutex = RT_NULL;

/* ??1?? */
static void thread1_entry(void* parameter)
{
    rt_thread_delay(10);
	  rt_err_t result;
	  //while(1)
		//{
	     //result = rt_mutex_take(mutex, RT_WAITING_FOREVER); 	  
       //if (result == RT_EOK)
       //{
			 //rt_kprintf("thread1 has take mutex\r\n");
			 rt_kprintf("tid2: %d tid3 %d\r\n",tid2->current_priority, tid3->current_priority);
			 rt_thread_delay(100);
			 //rt_kprintf("thread1 will release mutex\r\n");
       //rt_mutex_release(mutex);							 					  
       //}
	  //}
}

static void thread2_entry(void* parameter)
{
    rt_err_t result;

    rt_thread_delay(5);

    while (1)
    {
			  
        result = rt_mutex_take(mutex, RT_WAITING_FOREVER);        
        if (result == RT_EOK)
        {
					  rt_kprintf("thread2 has take mutex\r\n");
					  rt_thread_delay(1000);
					  rt_kprintf("thread2 will release mutex\r\n");
            rt_mutex_release(mutex);			 
					 					  
        }
    }
}

static void thread3_entry(void* parameter)
{
    rt_tick_t tick;
    rt_err_t result;
    while (1)
    {
        result = rt_mutex_take(mutex, RT_WAITING_FOREVER);
        rt_kprintf("thread3 has take mutex 1 \r\n");			
        result = rt_mutex_take(mutex, RT_WAITING_FOREVER);
			  rt_kprintf("thread3 has take mutex 2\r\n");
         
			
			  tick = rt_tick_get();
				while (rt_tick_get() - tick < 500) ;
				rt_kprintf("thread3 will release mutex 2\r\n");
				rt_mutex_release(mutex);
					
				rt_kprintf("thread3 will release mutex 1\r\n");
				rt_mutex_release(mutex);				
		
    }
}


int main()
{

    mutex = rt_mutex_create("mutex", RT_IPC_FLAG_FIFO);
    if (mutex == RT_NULL)
    {
        rt_kprintf("mutex has some wrong");
        return 0;
    }

   
    tid1 = rt_thread_create("t1",
        thread1_entry, /* ?????thread1_entry */
        RT_NULL, /* ?????RT_NULL */
        THREAD_STACK_SIZE, THREAD_PRIORITY - 1, THREAD_TIMESLICE);
    if (tid1 != RT_NULL)
        rt_thread_startup(tid1);
  

    /* ????2 */
    tid2 = rt_thread_create("t2",
        thread2_entry, /* ?????thread2_entry */
        RT_NULL, /* ?????RT_NULL */
        THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
    if (tid2 != RT_NULL)
        rt_thread_startup(tid2);


    /* ????3 */
    tid3 = rt_thread_create("t3",
        thread3_entry, /* ?????thread3_entry */
        RT_NULL, /* ?????RT_NULL */
        THREAD_STACK_SIZE, THREAD_PRIORITY + 1, THREAD_TIMESLICE);
    if (tid3 != RT_NULL)
        rt_thread_startup(tid3);


    return 0;
}

